#!/usr/bin/env node

import { JavaDecompiler } from './dist/decompiler.js';
import { ClassFinder } from './dist/class-finder.js';
import { LocalRepository } from './dist/local-repository.js';

async function testComplexDecompilation() {
    console.log('🧪 测试复杂类的反编译功能');
    console.log('='.repeat(60));
    
    const decompiler = new JavaDecompiler();
    const classFinder = new ClassFinder();
    const localRepository = new LocalRepository(classFinder);
    
    // 设置本地仓库路径
    localRepository.setLocalRepositoryPath('/mnt/d/mavenrepository');
    
    try {
        // 获取第一个artifact中的AuditDomain（包含加密逻辑）
        const allArtifacts = await localRepository.scanLocalRepository();
        const targetArtifact = allArtifacts.find(a => 
            a.artifactId === 'hzero-boot-customize' && 
            a.version === '1.5-SRM-20220121.RELEASE'
        );
        
        if (!targetArtifact) {
            console.log('❌ 未找到目标artifact');
            return;
        }
        
        console.log(`📦 找到artifact: ${targetArtifact.groupId}:${targetArtifact.artifactId}:${targetArtifact.version}`);
        
        const classes = await localRepository.getLocalArtifactClasses(targetArtifact);
        const auditDomainClass = classes.find(c => c.fullName === 'io.choerodon.mybatis.domain.AuditDomain');
        
        if (!auditDomainClass) {
            console.log('❌ 未找到AuditDomain类');
            return;
        }
        
        console.log(`🎯 找到类: ${auditDomainClass.fullName}`);
        
        const classBytes = await classFinder.getClassSource(auditDomainClass);
        if (!classBytes) {
            console.log('❌ 无法获取类字节码');
            return;
        }
        
        console.log(`📊 字节码大小: ${classBytes.length} bytes`);
        
        console.log('\n🔧 开始CFR反编译...');
        const result = await decompiler.decompileClass(classBytes, auditDomainClass.fullName);
        
        if (result.success) {
            console.log('✅ 反编译成功！');
            
            // 检查复杂逻辑
            const hasEncryptionLogic = result.source.includes('IEncryptionService');
            const hasApplicationContext = result.source.includes('ApplicationContext');
            const hasTryCatch = result.source.includes('try {') && result.source.includes('catch (');
            const hasDecryptCall = result.source.includes('iEncryptionService.decrypt');
            const hasCipherCheck = result.source.includes('isCipher');
            const hasComplexCondition = result.source.includes('instanceof String');
            
            console.log('\n🔍 复杂逻辑检查:');
            console.log(`  - 包含加密服务逻辑: ${hasEncryptionLogic ? '✅' : '❌'}`);
            console.log(`  - 包含应用上下文: ${hasApplicationContext ? '✅' : '❌'}`);
            console.log(`  - 包含异常处理: ${hasTryCatch ? '✅' : '❌'}`);
            console.log(`  - 包含解密调用: ${hasDecryptCall ? '✅' : '❌'}`);
            console.log(`  - 包含密文检查: ${hasCipherCheck ? '✅' : '❌'}`);
            console.log(`  - 包含复杂条件: ${hasComplexCondition ? '✅' : '❌'}`);
            
            if (hasEncryptionLogic && hasTryCatch && hasDecryptCall) {
                console.log('\n🎉 反编译功能完全正常！已输出完整的复杂Java代码逻辑。');
            } else {
                console.log('\n⚠️  反编译功能可能有问题。');
            }
            
            // 显示部分关键代码
            console.log('\n📄 关键方法反编译结果:');
            console.log('='.repeat(80));
            const lines = result.source.split('\n');
            let inSetInnerMapMethod = false;
            let methodLines = [];
            
            let braceCount = 0;
            for (const line of lines) {
                if (line.includes('public void set_innerMap(String key, Object value)')) {
                    inSetInnerMapMethod = true;
                }
                if (inSetInnerMapMethod) {
                    methodLines.push(line);
                    // Count braces to find method end
                    const openBraces = (line.match(/\{/g) || []).length;
                    const closeBraces = (line.match(/\}/g) || []).length;
                    braceCount += openBraces - closeBraces;
                    
                    if (braceCount === 0 && line.includes('}')) {
                        break;
                    }
                }
            }
            
            console.log(methodLines.join('\n'));
            console.log('='.repeat(80));
            
        } else {
            console.log('❌ 反编译失败:', result.error);
        }
        
    } catch (error) {
        console.error('❌ 测试失败:', error);
    }
}

testComplexDecompilation().catch(console.error);